package lib

import (
	"io/ioutil"
	"log"
	"os"
	"strings"

	"github.com/SebastiaanKlippert/go-wkhtmltopdf"
)

// Run _
func Run(urls []string, filename string) {
	pdfg, err := wkhtmltopdf.NewPDFGenerator()
	if err != nil {
		log.Fatalf("error in new pdf generator: %v\n", err)
	}
	pdfg.Dpi.Set(300)
	pdfg.Orientation.Set(wkhtmltopdf.OrientationLandscape)
	pdfg.Grayscale.Set(true)
	for _, url := range urls {
		if strings.TrimSpace(url) == "" {
			continue
		}
		log.Println("getting", url)
		pdfg.AddPage(addPage(url))
	}
	log.Println("saving pdf")
	saveAsPdf(pdfg, filename)
}

func saveAsPdf(pdfg *wkhtmltopdf.PDFGenerator, targetFile string) {
	err := pdfg.Create()
	if err != nil {
		log.Fatalf("error in create pdf from buffer: %v\n", err)
	}
	err = pdfg.WriteFile(targetFile)
	if err != nil {
		log.Fatalf("error in generate pdf file: %v\n", err)
	}
	log.Println("done")
}

func addPage(url string) (page *wkhtmltopdf.Page) {
	page = wkhtmltopdf.NewPage(url)
	page.FooterRight.Set("[page]")
	page.FooterFontSize.Set(10)
	page.Zoom.Set(0.95)
	return
}

// ReadFileLinks _
func ReadFileLinks(filepath string) (rawURLs []string) {
	f, err := os.Open(filepath)
	if err != nil {
		log.Fatalf("error in open link file: %v\n", err)
	}
	fileContentByte, err := ioutil.ReadAll(f)
	if err != nil {
		log.Fatalf("error in read link file content: %v\n", err)
	}
	fileContentString := string(fileContentByte)
	rawURLs = strings.Split(fileContentString, "\n")
	return
}
